<style lang="less">
    @import '../../../styles/common.less';
    @import './edit.less';
</style>
<template>
    <div>
        <Row>
            <Col span="18">
            <Card>
                <Form :label-width="80">
                    <FormItem label="文章标题">
                        <Input v-model="fields.title" icon="android-list"/>
                    </FormItem>
                    <FormItem label="副标题">
                        <Input v-model="fields.sub_title" icon="android-list"/>
                    </FormItem>
                    <FormItem label="文章分类">
                        <Cascader :data="classificationList" v-model="fields.category_id"></Cascader>
                    </FormItem>
                </Form>
                <div class="margin-top-20">
                    <script id="ueditor" name="content" type="text/plain"></script>
                </div>
            </Card>
            </Col>
            <Col span="6" class="padding-left-10">
            <Card>
                <p slot="title">
                    <Icon type="paper-airplane"></Icon>
                    发布
                </p>
                <p class="margin-top-10">
                    <Icon type="android-time"></Icon>&nbsp;&nbsp;状&nbsp;&nbsp;&nbsp; 态：
                    <Select size="small" style="width:90px" v-model="fields.status">
                        <Option v-for="(key, value) in articleStateList" :value="value" :key="value">{{ key }}</Option>
                    </Select>
                </p>
                <p class="margin-top-10">
                    <Icon type="eye"></Icon>&nbsp;&nbsp;公开度：&nbsp;<b>{{ opennessList[fields.openness] }}</b>
                    <Button v-show="!editOpenness" size="small" @click="handleEditOpenness" type="text">修改</Button>
                    <transition name="openness-con">
                        <div v-show="editOpenness" class="openness-radio-con">
                            <RadioGroup v-model="fields.openness" vertical>
                                <Radio label="public">公开
                                    <Checkbox v-show="fields.openness === 'public'" v-model="fields.is_top">置顶这篇文章</Checkbox>
                                </Radio>
                                <Radio label="private">私密</Radio>
                            </RadioGroup>
                            <div>
                                <Button type="primary" @click="handleSaveOpenness">确认</Button>
                                <Button type="ghost" @click="cancelEditOpenness">取消</Button>
                            </div>
                        </div>
                    </transition>
                </p>
                <p class="margin-top-10">
                    <Icon type="ios-calendar-outline"></Icon>&nbsp;&nbsp;
                    <span v-if="fields.published_at == '' || fields.published_at == undefined">立即发布</span>
                    <span v-else>定时：{{ fields.published_at }}</span>
                    <Button v-show="!editPublishTime" size="small" @click="handleEditPublishTime" type="text">修改</Button>
                    <transition name="publish-time">
                        <div v-show="editPublishTime" class="publish-time-picker-con">
                            <div class="margin-top-10">
                                <DatePicker @on-change="setPublishTime" :value="fields.published_at" type="datetime" placeholder="选择日期和时间" ></DatePicker>
                            </div>
                            <div class="margin-top-10">
                                <Button type="primary" @click="handleSavePublishTime">确认</Button>
                                <Button type="ghost" @click="cancelEditPublishTime">取消</Button>
                            </div>
                        </div>
                    </transition>
                </p>
                <Row :gutter="5" class="margin-top-20 publish-button-con">
                    <Col span="12"><Button @click="handlePreview" long>预览</Button></Col>
                    <Col span="12"><Button @click="handlePublish" long :loading="publishLoading" icon="ios-checkmark" type="primary">保存</Button></Col>
                </Row>
            </Card>
            <div class="margin-top-10">
                <Card>
                    <p slot="title">
                        <Icon type="ios-pricetags-outline"></Icon>
                        标签
                    </p>
                    <Row>
                        <Col span="18">
                        <Select
                                v-model="fields.tag_ids"
                                multiple
                                filterable
                                remote
                                :label="seletedTagsLabel"
                                :remote-method="remoteTagList"
                                placeholder="搜索标签"
                                :loading="tagLoading">
                            <Option v-for="(option, index) in tagList" :value="option.value" :key="index">{{option.label}}</Option>
                        </Select>
                        </Col>
                        <Col span="6" class="padding-left-10">
                        <Button v-show="!addingNewTag" @click="handleAddNewTag" type="ghost">新建</Button>
                        </Col>
                    </Row>
                    <transition name="add-new-tag">
                        <div v-show="addingNewTag" class="add-new-tag-con">
                            <Col span="14">
                            <Input v-model="newTagName" placeholder="请输入标签名" />
                            </Col>
                            <Col class="add-new-tag-a" span="5">
                            <a @click="createNewTag">添加</a>
                            </Col>
                            <Col class="add-new-tag-a" span="5">
                            <a @click="cancelCreateNewTag">取消</a>
                            </Col>
                        </div>
                    </transition>
                </Card>
            </div>
            </Col>
        </Row>
    </div>
</template>

<script>
    import util from '@/libs/util';
    import storage from '@/libs/storage';

    export default {
        name: 'admin-cms-article-edit',
        data () {
            return {
                articleId: '',
                fields: {
                    title: '',
                    sub_title: '',
                    content: '',
                    openness: 'public',
                    status: 'draft',
                    published_at: '',
                    category_id: 0,
                    tag_ids: [],
                    is_top: false
                },
                ueditor: null,
                classificationList: [],
                articleStateList: {
                    draft: '草稿',
                    wait_audit: '待审核'
                },
                opennessList: {
                    public: '公开',
                    private: '私密',
                    password: '密码访问'
                },
                editOpenness: false,
                publishTime: '',
                publishTimeType: 'immediately',
                editPublishTime: false,  // 是否正在编辑发布时间
                publishLoading: false,

                tagList: [],  // 所有标签列表
                addingNewTag: false,  // 添加新标签
                newTagName: '', // 新建标签名
                tagLoading: false,
                seletedTagsLabel: [],
            };
        },
        methods: {
            handleArticletitleBlur () {
                if (this.fields.title.length == 0) {
                    this.$Message.error('文章标题不可为空哦');
                }
            },
            handleEditOpenness () {
                this.editOpenness = !this.editOpenness;
            },
            handleSaveOpenness () {
                this.editOpenness = false;
            },
            cancelEditOpenness () {
                this.editOpenness = false;
            },
            handleEditPublishTime () {
                this.editPublishTime = !this.editPublishTime;
            },
            handleSavePublishTime () {
                this.publishTimeType = 'timing';
                this.editPublishTime = false;
            },
            cancelEditPublishTime () {
                this.publishTimeType = 'immediately';
                this.editPublishTime = false;
            },
            setPublishTime (datetime) {
                this.fields.published_at = datetime;
            },

            canPublish () {
                console.log('fields', this.fields);
                if (this.fields.title.length === 0) {
                    this.$Message.error('请输入文章标题');
                    return false;
                } else if (this.fields.category_id.length === 0) {
                    this.$Message.error('请选择文章分类');
                    return false;
                } else {
                    return true;
                }
            },

            handlePreview () {
                if (this.canPublish()) {
                    storage.set('articlePreviewData', this.fields);
                    this.$router.push({
                        name: 'admin-cms-article-preview'
                    });
                }
            },

            saveArticle (data) {
                data.category_id = data.category_id.pop();
                util.api().put(`/admin/api/cms/articles/${this.articleId}`, data).then((resp) => {
                    if (resp.data.status == true) {
                        this.$Notice.success({ title: resp.data.message });
                        this.$store.commit('removeTag', 'admin-cms-article-edit');
                        this.$router.push({
                            name: 'admin-cms-article-list'
                        });
                    } else {
                        this.$Notice.error({ title: resp.data.message });
                    }
                    this.publishLoading = false;
                }).catch((e) => {
                    util.handleApiException(e, this, '修改文章失败');
                    this.publishLoading = false;
                })
            },

            handlePublish () {
                if (this.canPublish()) {
                    this.publishLoading = true;
                    let params = {};
                    Object.assign(params, this.fields);
                    this.saveArticle(params);
                }
            },

            handleAddNewTag () {
                this.addingNewTag = !this.addingNewTag;
            },

            createNewTag () {
                if (this.newTagName.length !== 0) {
                    util.api().post('/admin/api/cms/tags', {name: this.newTagName}).then((resp) => {
                        if (resp.data.status == true) {
                            setTimeout(() => {
                                this.fields.tag_ids.push(resp.data.data.id);
                            }, 100);

                            this.tagList.push({
                                value: resp.data.data.id,
                                label: resp.data.data.name
                            });

                            this.newTagName = '';
                            this.addingNewTag = false;
                            this.$Message.success(resp.data.message);
                        } else {
                            this.$Message.error(resp.data.message);
                        }
                        console.log(resp.data);
                    }).catch((e) => {
                        util.handleApiException(e, this, '添加标签失败');
                        this.addingNewTag = false;
                    });
                } else {
                    this.$Message.error('请输入标签名');
                }
            },

            cancelCreateNewTag () {
                this.newTagName = '';
                this.addingNewTag = false;
            },

            remoteTagList (query) {
                if (query !== '') {
                    this.tagLoading = true;
                    util.api().get(`/admin/api/cms/tags?keyword=${query}`).then((resp) => {
                        this.tagLoading = false;
                        console.log(resp.data);
                        const currentTagList = this.tagList.map(item => { return item.value; });
                        console.log(currentTagList);

                        for (let i in resp.data.data) {
                            if (currentTagList.indexOf(resp.data.data[i].id) < 0) {
                                this.tagList.push({
                                    value: resp.data.data[i].id,
                                    label: resp.data.data[i].name
                                });
                            }
                        }
                    }).catch((e) => {
                        if (e.response) {
                            this.$Notice.error({ title: '获取标签失败', desc: e.response.data.message});
                        } else {
                            this.$Message.error('获取标签失败');
                        }
                        this.tagLoading = false;
                    })
                }
            },

            getCategories (id, callback) {
                util.api().get(`/admin/api/categories/${id}/selected/parents`).then((resp) => {
                    const formatTree = (arr) => {
                        let categories = [];
                        for (let i in arr) {
                            let node = {};
                            node.value = arr[i].id;
                            node.label = arr[i].name;
                            node.disabled = arr[i].disabled;
                            if (arr[i].hasOwnProperty('children')) {
                                node.children = formatTree(arr[i].children);
                            }
                            if (id == node.value) {
                                node.selected = true;
                            }
                            categories.push(node);
                        }
                        return categories;
                    };

                    const tree = formatTree(resp.data.data.tree);

                    let selected = [];
                    for (let i in resp.data.data.parents) {
                        selected.push(resp.data.data.parents[i].id);
                    }

                    callback(tree, selected);
                }).catch((e) => {
                    if (e.response) {
                        this.$Notice.error({ title: '获取分类失败', desc: e.response.data.message});
                    } else {
                        this.$Message.error('获取分类失败');
                    }
                    callback([], []);
                });
            },

            initTagList (ids, callback) {
                util.api().get(`/admin/api/cms/tags?ids=${ids}`).then((resp) => {
                    this.tagLoading = false;
                    const currentTagList = this.tagList.map(item => { return item.value; });
                    for (let i in resp.data.data) {
                        if (currentTagList.indexOf(resp.data.data[i].id) < 0) {
                            this.tagList.push({
                                value: resp.data.data[i].id,
                                label: resp.data.data[i].name
                            })
                        }
                    }
                    callback();
                }).catch((e) => {
                    util.handleApiException(e, this, '获取标签失败');
                    this.tagLoading = false;
                    callback();
                })
            },

            initUEditor () {
                let vm = this;
                this.$nextTick(() => {
                    vm.ueditor = UE.getEditor('ueditor');
                    vm.ueditor.ready(function() {
                        //设置编辑器的内容
                        vm.ueditor.setContent(vm.fields.content);
                    });
                    vm.ueditor.addListener('contentChange', function () {
                        vm.fields.content = vm.ueditor.getContent();
                    });
                })
            }
        },

        beforeRouteEnter (to, from, next) {
            next(vm => {
                if (vm.ueditor) {
                    try {
                        vm.ueditor.execCommand('source');
                        vm.ueditor.execCommand('source');
                    } catch (e) {
                        console.log('更新编辑框内容显示')
                    }
                }
            });
        },

        mounted () {
            /**
             * 获取文章详情
             */
            const articleId = this.$route.query.articleId;
            util.api().get(`/admin/api/cms/articles/${articleId}`).then((resp) => {
                if (resp.data.status == true) {
                    this.articleId = resp.data.data.id;
                    this.fields = resp.data.data;
                    this.initTagList(resp.data.data.tag_ids.join(','), () => {
                        this.tagList.forEach(item => {
                            if (resp.data.data.tag_ids.indexOf(item.value) >= 0) {
                                this.seletedTagsLabel.push(item.label);
                            }
                        });

                        let categoryId = this.fields.category_id;
                        if (categoryId instanceof Array) {
                            categoryId = categoryId.pop();
                        }

                        this.getCategories(categoryId, (tree, selected) => {
                            setTimeout(() => {
                                this.fields.category_id = selected;
                            }, 100);

                            this.classificationList = tree;
                        });

                        // 初始化编辑器
                        this.initUEditor();
                    });
                } else {
                    this.$Message.error(resp.data.message);
                }
            }).catch((e) => {
                util.handleApiException(e, this, '获取文章详情失败');
            });
        }
    };
</script>
